const Client = require("ssh2").Client

const SSHUtil = {
    conn:null    
};

SSHUtil.init = function(server){
    if(SSHUtil.conn == null){
        SSHUtil.conn = new Client();
    }
    return new Promise(function(resolve,reject){ 
        SSHUtil.connetc(server,function(){
            console.log("shell 已成功登录");
            resolve(SSHUtil.conn);
        })      
    });
}

SSHUtil.connetc = function(server,callBack){
    SSHUtil.conn.on('ready', function() {        
        callBack()
    }).connect(server);
}

SSHUtil.close = function(){
    SSHUtil.conn.on('end', function() {
		
	});
	SSHUtil.conn.end();
}

SSHUtil.exec = function({cmd,success,key}) {  
    
    SSHUtil.conn.exec(cmd, function (err, stream) {
        stream.on('close', function(code, signal) {
            //console.log(`cmd[${cmd}]`+code);
        }).on('data', function(data) {
            //console.log(`STDOUT[${cmd}]:`);
            success(data,key);
        }).stderr.on('data', function(data) {
            console.error(`STDERR[${cmd}]:` + data);
        });        
    });
};


export default SSHUtil;